package westh.ilib.service;

import java.security.SecureRandom;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.sf.json.*;

public class ResourceRanking {
	
	private List jsonArrayList=null;
	private int numOfFields=1;
	private JSONArray[] rscJsonArray=null;
	private Set existIds=null;
	private int numOfRscs=0;
	private SecureRandom random=null;
	
	public ResourceRanking(List jsonArrayList){
		this.jsonArrayList=jsonArrayList;
		this.numOfFields=jsonArrayList.size();
		rscJsonArray=new JSONArray[numOfFields];
		for(int i=0;i<numOfFields;i++){
			rscJsonArray[i]=(JSONArray)jsonArrayList.get(i);
			numOfRscs+=rscJsonArray[i].size();
		}
		existIds=new HashSet();
		random=new SecureRandom();
	}
	/**
	 * 
	 * @return
	 */
	public String mergeResults(){
		if(jsonArrayList.size()==0) return "[]";
		JSONArray finalResult=new JSONArray();
		for(int i=0;i<numOfRscs;i++){
			random.setSeed((i+1)*100000);
			int field=random.nextInt(numOfFields);
			JSONObject json=(JSONObject)((JSONArray)jsonArrayList.get(field)).remove(0);
			String rscId=json.getString("rscId");
			//String rscId="1";
			if(!existIds.contains(rscId)){
				existIds.add(rscId);
				finalResult.add(json);
			}
			if(((JSONArray)jsonArrayList.get(field)).size()==0){
				jsonArrayList.remove(field);
				numOfFields--;
			}
			if(numOfFields==0) break;
		}
		return finalResult.toString();
	}
	

	

}
